package com.ldy.core.util;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ldy.core.entity.Sequence;
import com.ldy.core.service.SequenceService;
/**
 * 水流号管理
 * @author lindeyi
 */
public class SequenceUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(SequenceUtil.class);

	private static final String NUMBER = "{number}";
	private static final String CYCLE = "{cycle}";
	
	/**
	 * 获取流水号
	 * @param key
	 * @return
	 */
	public static synchronized String get(String key) {
		try {
			SequenceService service = BeanUtils.getBean(SequenceService.class);
			Sequence sequence = service.getById(key);
			if (sequence == null) {
				logger.error("{}:流水号未管理", key);
				return null;
			}
			String format = sequence.getFormat();
			String cycle = new SimpleDateFormat(sequence.getCycle()).format(new Date());
			format = format.replace(CYCLE, cycle);
			
			Long size = sequence.getSize();
			Long increase = sequence.getIncrease();
			Long maxValue = sequence.getMaxValue();
			String currentCycle = sequence.getCurrentCycle();
			long val = 1;
			if (!cycle.equals(currentCycle)) {
				// 周期切换
				val = 1;
			} else {
				val = maxValue+increase;
			}
			
			if (size > 0) {
				int pow = (int) Math.pow(10, size);
				String number = MessageFormat.format("{0,number," + String.valueOf(pow).substring(1) + "}", val);
				format = format.replace(NUMBER, number);
			} else {
				format = format.replace(NUMBER, String.valueOf(val));
			}
			sequence.setMaxValue(val);
			sequence.setCurrentCycle(cycle);
			service.updateById(sequence);
			logger.info("生成流水号:{}", format);
			return format;
		}catch (Exception e) {
			logger.error("", e);
		}
		return null;
		
	}
}
